
package com.jf.cloud.order.controller.app;

import com.jf.cloud.api.delivery.feign.StationFeignClient;
import com.jf.cloud.api.delivery.vo.StationVO;
import com.jf.cloud.api.feign.SearchOrderFeignClient;
import com.jf.cloud.api.order.constant.OrderStatus;
import com.jf.cloud.api.user.vo.UserTagApiVO;
import com.jf.cloud.api.vo.EsPageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.constant.DeliveryType;
import com.jf.cloud.common.order.dto.OrderSearchDTO;
import com.jf.cloud.common.order.vo.EsOrderVO;
import com.jf.cloud.common.order.vo.OrderSelfStationVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.order.dto.OrderStationDTO;
import com.jf.cloud.order.service.OrderSelfStationService;
import com.jf.cloud.order.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import ma.glasnost.orika.MapperFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Lanhai
 */
@RestController("appMyStationController")
@RequestMapping("/my_station_order")
@Tag(name = "用户自提订单接口")
public class MyStationOrderController {
    private final Logger LOGGER = LoggerFactory.getLogger(MyStationOrderController.class);

    @Autowired
    private StationFeignClient stationFeignClient;

    @Autowired
    private SearchOrderFeignClient searchOrderFeignClient;

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderSelfStationService orderSelfStationService;

    @GetMapping("/station_detail")
    @Operation(summary = "订单详情自提信息", description = "根据订单号获取订单详情自提信息")
    @Parameter(name = "orderId", description = "订单号", required = true)
    public ServerResponseEntity<OrderSelfStationVO> orderDetail(@RequestParam(value = "orderId") Long orderId,
                                                                @RequestParam(value = "lat", required = false) Double lat,
                                                                @RequestParam(value = "lng", required = false) Double lng) {
        OrderSelfStationVO orderSelfStationVO = orderSelfStationService.getStationByOrderId(orderId);
        if(lat != null && lng != null){
            LOGGER.info("根据经纬度计算实时距离，lat:{},lng:{}", lat, lng);
            Double distance = orderSelfStationService.setStationDistance(orderSelfStationVO.getStationId(), lat, lng);
            orderSelfStationVO.setDistance(distance);
        }
        return ServerResponseEntity.success(orderSelfStationVO);
    }

    @GetMapping("/get_order_by_station_id")
    @Operation(summary = "用户扫自提点码" , description = "用户扫自提点码获取自提订单列表")
    @Parameter(name = "stationId", description = "自提点id" , required = true)
    public ServerResponseEntity<EsPageVO<EsOrderVO>> getOrderListByStationId(@ParameterObject OrderSearchDTO orderSearchDTO) {
        Long userId = AuthUserContext.get().getUserId();
        StationVO stationVO = stationFeignClient.getStation(orderSearchDTO.getStationId()).getData();
        if(Objects.isNull(stationVO)){
            throw new LuckException("该自提点不存在");
        }
        orderSearchDTO.setUserId(userId);
        orderSearchDTO.setWaitPurchase(0);
        orderSearchDTO.setOrderMold(1);
        orderSearchDTO.setShopId(stationVO.getShopId());
        EsPageVO<EsOrderVO> page = searchOrderFeignClient.pageOrder(orderSearchDTO).getData();
        if(page.getList() != null){
            List<OrderSelfStationVO> orderSelfStationVOList = orderSelfStationService.getOrderSelfStationByStationIdOrShopId(userId, orderSearchDTO.getStationId(), null);
            LOGGER.info("根据订单id获取自提信息，orderSelfStationVOList:{}", orderSelfStationVOList);
            Map<Long, OrderSelfStationVO> orderSelfStationVOMap = orderSelfStationVOList.stream().collect(Collectors.toMap(OrderSelfStationVO::getOrderId, (k) -> k));
            page.getList().forEach(s-> s.setOrderSelfStationVO(orderSelfStationVOMap.get(s.getOrderId())));
        }
        return ServerResponseEntity.success(page);
    }

    @GetMapping("/get_order_by_shop_id")
    @Operation(summary = "用户扫商家码" , description = "用户扫商家码获取自提订单列表")
    @Parameter(name = "shopId", description = "店铺id" , required = true)
    public ServerResponseEntity<EsPageVO<EsOrderVO>> getOrderListByShopId(@ParameterObject OrderSearchDTO orderSearchDTO) {
        Long userId = AuthUserContext.get().getUserId();
        orderSearchDTO.setUserId(userId);
        orderSearchDTO.setWaitPurchase(0);
        EsPageVO<EsOrderVO> page = searchOrderFeignClient.pageOrder(orderSearchDTO).getData();
        List<OrderSelfStationVO> orderSelfStationVOList = orderSelfStationService.getOrderSelfStationByStationIdOrShopId(userId, null, orderSearchDTO.getShopId());
        Map<Long, OrderSelfStationVO> orderSelfStationVOMap = orderSelfStationVOList.stream().collect(Collectors.toMap(OrderSelfStationVO::getOrderId, (k) -> k));
        page.getList().forEach(s-> s.setOrderSelfStationVO(orderSelfStationVOMap.get(s.getOrderId())));
        return ServerResponseEntity.success(page);
    }

    @PutMapping("/order_station_by_order_id")
    @Operation(summary = "用户提货操作" , description = "用户提货操作")
    public ServerResponseEntity<Boolean> orderStationByOrderId(@RequestBody OrderStationDTO orderStationDTO) {
        return ServerResponseEntity.success(orderService.orderStationByOrderId(orderStationDTO.getOrderIds(), AuthUserContext.get().getUserId(), orderStationDTO.getStationId()));
    }

//    @GetMapping("/getStationInfoByOrderNumber")
//    @Operation(summary = "我的订单自提信息接口" , description = "根据订单号获取订单详情自提信息")
//    @Parameter(name = "orderNumber", description = "订单号" , required = true)
//    public ServerResponseEntity<MyOrderDto> getStationDetailByOrderNumber(@RequestParam(value = "orderNumber") String orderNumber) {
//        OrderSelfStation orderSelfStation = orderSelfStationService.getOne(new LambdaQueryWrapper<OrderSelfStation>()
//                .eq(OrderSelfStation::getOrderNumber, orderNumber));
//        OrderSelfStationDto orderSelfStationDto = mapperFacade.map(orderSelfStation, OrderSelfStationDto.class);
//        Order order = orderService.getOrderAndOrderItemByOrderNumber(orderNumber);
//        //获取订单项的退款信息
//        orderService.getOrderItemRefundStatus(order);
//        MyOrderDto myOrderDto = mapperFacade.map(order, MyOrderDto.class);
//        myOrderDto.setOrderItemDtos(mapperFacade.mapAsList(order.getOrderItems(), MyOrderItemDto.class));
//        myOrderDto.setOrderSelfStationDto(orderSelfStationDto);
//        return ServerResponseEntity.success(myOrderDto);
//    }
}
